<template>
    <div class="task-form-container">
        <!-- 页面头部 -->
        <div class="page-header">
            <div class="header-content">
                <div class="header-left">
                    <h2>{{ isEdit ? '编辑任务' : '新增任务' }}</h2>
                </div>
                <div class="header-right">
                    <el-button @click="handleCancel">
                        <el-icon>
                            <ArrowLeft />
                        </el-icon>
                        返回
                    </el-button>
                </div>
            </div>
        </div>

        <!-- 表单内容 -->
        <div class="form-content">
            <el-card shadow="never" class="form-card">
                <el-form ref="taskFormRef" :model="formData" :rules="formRules" label-width="140px" class="task-form">
                    <el-row :gutter="20">
                        <!-- 任务代码 -->
                        <el-col :span="12">
                            <el-form-item label="任务代码:" prop="taskCode">
                                <el-input v-model="formData.taskCode" placeholder="输入任务代码" />
                            </el-form-item>
                        </el-col>
                        <!-- 语言 -->
                        <el-col :span="12">
                            <el-form-item label="语言:" prop="language">
                                <el-select v-model="formData.language" placeholder="请选择语言" style="width: 100%">
                                    <el-option v-for="option in LANGUAGE_OPTIONS" :key="option.value"
                                        :label="option.label" :value="option.value" />
                                </el-select>
                            </el-form-item>
                        </el-col>

                        <!-- 任务名称 -->
                        <el-col :span="12">
                            <el-form-item label="任务名称:" prop="taskName">
                                <el-input v-model="formData.taskName" placeholder="输入任务名称" />
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row :gutter="20">
                        <!-- 任务类型 -->
                        <el-col :span="12">
                            <el-form-item label="任务类型:" prop="taskType">
                                <el-select v-model="formData.taskType" placeholder="请选择任务类型" style="width: 100%">
                                    <el-option v-for="option in TASK_TYPE_OPTIONS" :key="option.value"
                                        :label="option.label" :value="option.value" />
                                </el-select>
                            </el-form-item>
                        </el-col>

                        <!-- 完成数量 -->
                        <el-col :span="12">
                            <el-form-item label="完成数量:" prop="completionQuantity">
                                <el-input-number v-model="formData.completionQuantity" :min="1" :max="999999"
                                    placeholder="输入完成数量" style="width: 100%" />
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row :gutter="20">
                        <!-- 奖励类型 -->
                        <el-col :span="12">
                            <el-form-item label="奖励类型:" prop="rewardType">
                                <el-select v-model="formData.rewardType" placeholder="请选择奖励类型" style="width: 100%">
                                    <el-option v-for="option in REWARD_TYPE_OPTIONS" :key="option.value"
                                        :label="option.label" :value="option.value" />
                                </el-select>
                            </el-form-item>
                        </el-col>

                        <!-- 任务周期 -->
                        <el-col :span="12">
                            <el-form-item label="任务周期:" prop="taskCycle">
                                <el-select v-model="formData.taskCycle" placeholder="请选择任务周期" style="width: 100%">
                                    <el-option v-for="option in TASK_CYCLE_OPTIONS" :key="option.value"
                                        :label="option.label" :value="option.value" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <!-- 任务描述 -->
                    <el-form-item label="任务描述:" prop="taskDescription">
                        <el-input v-model="formData.taskDescription" type="textarea" :rows="4" placeholder="输入任务描述"
                            maxlength="100" show-word-limit />
                    </el-form-item>

                    <!-- 是否限时 -->
                    <el-form-item label="是否限时:" prop="isTimeLimited">
                        <el-switch v-model="formData.isTimeLimited" active-text="是" inactive-text="否" />
                    </el-form-item>

                    <!-- 时间限制相关字段 -->
                    <template v-if="formData.isTimeLimited">
                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="开始时间:" prop="startTime">
                                    <el-date-picker v-model="formData.startTime" type="datetime" placeholder="选择开始时间"
                                        format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DDTHH:mm:ss.sssZ"
                                        style="width: 100%" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="结束时间:" prop="endTime">
                                    <el-date-picker v-model="formData.endTime" type="datetime" placeholder="选择结束时间"
                                        format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DDTHH:mm:ss.sssZ"
                                        style="width: 100%" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </template>

                    <!-- 操作按钮 -->
                    <el-form-item>
                        <div class="form-actions">
                            <el-button @click="handleCancel">取消</el-button>
                            <el-button type="primary" @click="handleSubmit" :loading="loading">保存</el-button>
                        </div>
                    </el-form-item>
                </el-form>
            </el-card>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { ArrowLeft } from '@element-plus/icons-vue';
import { TaskFormData, TASK_TYPE_OPTIONS, REWARD_TYPE_OPTIONS, TASK_CYCLE_OPTIONS, LANGUAGE_OPTIONS } from '@/types/task';
import { createTask, updateTask, getTaskDetail } from '@/api/system/task';

const route = useRoute();
const router = useRouter();

const id = route.params.id as string;
const isEdit = computed(() => !!id);

// 表单引用
const taskFormRef = ref();
const loading = ref(false);

// 表单数据
const formData = reactive<TaskFormData>({
    taskCode: '',
    taskName: '',
    taskDescription: '',
    taskType: 1,
    completionQuantity: 1,
    rewardType: 1,
    rewardConfig: '',
    memberLevelIds: [],
    isTimeLimited: false,
    startTime: '',
    endTime: '',
    taskCycle: 1,
    language: 'zh-CN'
});

// 会员等级ID文本（用于显示和编辑）
const memberLevelIdsText = ref('');

// 表单验证规则
const formRules = {
    taskCode: [
        { required: true, message: '请输入任务代码', trigger: 'blur' },
        { max: 50, message: '任务代码最大长度50位', trigger: 'blur' }
    ],
    taskName: [
        { required: true, message: '请输入任务名称', trigger: 'blur' },
        { min: 2, max: 100, message: '任务名称长度2-100位', trigger: 'blur' }
    ],
    taskDescription: [
        { required: true, message: '请输入任务描述', trigger: 'blur' },
        { min: 2, max: 100, message: '任务描述长度2-100位', trigger: 'blur' }
    ],
    taskType: [
        { required: true, message: '请选择任务类型', trigger: 'change' }
    ],
    completionQuantity: [
        { required: true, message: '请输入完成数量', trigger: 'blur' },
        { type: 'number', min: 1, message: '完成数量必须大于0', trigger: 'blur' }
    ],
    rewardType: [
        { required: true, message: '请选择奖励类型', trigger: 'change' }
    ],
    taskCycle: [
        { required: true, message: '请选择任务周期', trigger: 'change' }
    ],
    language: [
        { required: true, message: '请选择语言', trigger: 'change' }
    ],
    startTime: [
        {
            validator: (rule: any, value: string, callback: Function) => {
                if (formData.isTimeLimited && !value) {
                    callback(new Error('请选择开始时间'));
                } else {
                    callback();
                }
            },
            trigger: 'change'
        }
    ],
    endTime: [
        {
            validator: (rule: any, value: string, callback: Function) => {
                if (formData.isTimeLimited && !value) {
                    callback(new Error('请选择结束时间'));
                } else if (formData.isTimeLimited && formData.startTime && value && new Date(value) <= new Date(formData.startTime)) {
                    callback(new Error('结束时间必须大于开始时间'));
                } else {
                    callback();
                }
            },
            trigger: 'change'
        }
    ]
};

// 处理会员等级ID变化
const handleMemberLevelIdsChange = (value: string) => {
    if (value.trim()) {
        formData.memberLevelIds = value.split(',').map(id => id.trim()).filter(id => id);
    } else {
        formData.memberLevelIds = [];
    }
};

// 提交表单
const handleSubmit = async () => {
    if (!taskFormRef.value) return;

    try {
        await taskFormRef.value.validate();

        await ElMessageBox.confirm(
            `确定要${isEdit.value ? '更新' : '保存'}此任务吗？`,
            '确认操作',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'success',
            }
        );

        loading.value = true;

        // 准备提交数据
        const submitData = { ...formData };

        // 如果不限时，清空时间字段
        if (!submitData.isTimeLimited) {
            submitData.startTime = '';
            submitData.endTime = '';
        }

        let res;
        if (isEdit.value) {
            // 编辑模式
            res = await updateTask({ id, ...submitData });
        } else {
            // 新增模式
            res = await createTask(submitData);
        }

        const responseData = res as any;
        if (responseData && responseData.code === 200) {
            ElMessage.success(`${isEdit.value ? '更新' : '保存'}成功`);
            router.push('/task-list');
        } else {
            const errorMsg = (responseData && responseData.msg) || `${isEdit.value ? '更新' : '保存'}失败`;
            ElMessage.error(errorMsg);
        }

    } catch (error) {
        if (error !== 'cancel') {
            console.error('保存任务失败:', error);
            ElMessage.error('操作失败，请稍后重试');
        }
    } finally {
        loading.value = false;
    }
};

// 取消操作
const handleCancel = () => {
    router.push('/task-list');
};

// 加载任务数据
const loadTaskData = async (taskId: string) => {
    try {
        loading.value = true;
        const res = await getTaskDetail(taskId);
        const responseData = res as any;

        if (responseData && responseData.code === 200 && responseData.data) {
            const taskData = responseData.data;

            // 填充表单数据
            Object.assign(formData, {
                taskCode: taskData.taskCode || '',
                taskName: taskData.taskName || '',
                taskDescription: taskData.taskDescription || '',
                taskType: taskData.taskType || 1,
                completionQuantity: taskData.completionQuantity || 1,
                rewardType: taskData.rewardType || 1,
                rewardConfig: taskData.rewardConfig || '',
                memberLevelIds: taskData.memberLevelIds || [],
                isTimeLimited: taskData.isTimeLimited || false,
                startTime: taskData.startTime || '',
                endTime: taskData.endTime || '',
                taskCycle: taskData.taskCycle || 1,
                language: taskData.language || 'zh-CN'
            });

            // 设置会员等级ID文本
            memberLevelIdsText.value = taskData.memberLevelIds ? taskData.memberLevelIds.join(',') : '';
        } else {
            const errorMsg = (responseData && responseData.msg) || '获取任务详情失败';
            ElMessage.error(errorMsg);
        }
    } catch (error) {
        console.error('获取任务详情失败:', error);
        ElMessage.error('获取任务详情失败，请稍后重试');
    } finally {
        loading.value = false;
    }
};

// 页面初始化
onMounted(() => {
    if (isEdit.value) {
        // 编辑模式：加载现有数据
        loadTaskData(id);
    }
});
</script>

<style scoped>
.task-form-container {
    padding: 20px;
    background-color: #f5f5f5;
    min-height: 100vh;
}

.page-header {
    border-radius: 8px;
    margin-bottom: 20px;
}

.header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.header-left h2 {
    margin: 0;
    color: #333;
    font-size: 24px;
}

.form-content {
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.form-card {
    border-radius: 8px;
}

.task-form {
    padding: 30px;
}


.form-actions {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .task-form-container {
        padding: 10px;
    }

    .header-content {
        flex-direction: column;
        gap: 16px;
        align-items: flex-start;
    }

    .task-form {
        padding: 20px;
    }

    .form-actions {
        justify-content: center;
    }
}
</style>
